"""
$Id: graph.py 2 2007-03-04 19:08:44Z sidnei.da.silva $
"""

import time
import threading
import logging
import matplotlib
matplotlib.use('TkAgg')
matplotlib.interactive(True)

import pylab
from voting import constants


class Graph(threading.Thread):

    def __init__(self, cond, data):
        threading.Thread.__init__(self)
        self.logger = logging.getLogger('voting.graph')
        self.cond = cond
        self.data = data
        self.shutdown = False

    def setup(self):
        self.logger.debug('Starting setup')
        self.manager = pylab.get_current_fig_manager()
        self.canvas = self.manager.canvas
        self.figure = self.canvas.figure
        self.axis = self.figure.add_subplot(111)
        self.axis.grid(True)
        self.canvas.draw()
        self.logger.debug('Finished setup')

    def stop(self):
        self.shutdown = True
        self.notify()

    def notify(self):
        self.cond.acquire()
        self.cond.notify()
        self.cond.release()

    def run(self):
        try:
            self.setup()
            self.logger.info('Started')
            try:
                while True:
                    self.cond.acquire()
                    try:
                        self.logger.debug('Waiting for condition')
                        self.cond.wait()
                        self.logger.debug('Condition triggered')
                        if self.shutdown:
                            self.manager.destroy()
                            break
                        self.plot()
                    finally:
                        self.cond.release()
            except:
                self.logger.exception('Exception...')
        finally:
            self.logger.info('Finished')

    def plot(self):
        self.logger.debug('Starting plot')
        if not self.data:
            return
        self.axis.clear()
        for key in constants.VALID_CHOICES:
            value = self.data.get(key, 0)
            self.axis.bar(key, value, 0.35)
        self.axis.set_xlabel('Choice')
        self.axis.set_ylabel('Votes')
        self.axis.set_title('Statistics')
        self.canvas.draw()
        self.logger.debug('Finished plot')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    cond = threading.Condition()
    data = {0:5,
            1:10,
            2:4,
            3:8,
            4:17}


    g = Graph(cond, data)
    g.setDaemon(True)
    g.start()
    g.notify()

    raw_input('Press a key to continue')
    data[3] = 19
    g.notify()

    raw_input('Press a key to continue')
    data[2] = 11
    g.notify()

    raw_input('Press a key to exit')
    g.stop()
